/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fb.admin.controller;

import com.fb.common.ActionType;
import com.fb.common.CommonUtil;
import com.fb.common.RenderModel;
import com.fb.common.UserData;
import com.fb.common.UserRole;
import com.fb.common.UserType;
import com.fb.model.ActionModel;
import com.fb.model.SessionModel;
import com.fb.model.UserModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class AdminUserController extends HttpServlet {

    private static final Logger logger = Logger.getLogger(AdminUserController.class);
    public static final String STATIC_ICON_PATH = "/static/img/icon/";
    public static final String REMOTE_ICON_PATH = "/appstore/icon/";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminUserController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/ajax-add-new-user":
                content = ajaxAddNewUser(req, resp);
                break;
            case "/ajax-edit-user":
                content = ajaxEditUser(req, resp);
                break;
            case "/ajax-delete-user":
                content = ajaxDeleteUser(req, resp);
                break;
            case "/ajax-get-access":
                content = ajaxGetAccess(req, resp);
                break;
            case "/ajax-update-access":
                content = ajaxUpdateAccess(req, resp);
                break;
            case "/pass":
                content = renderChangePass(req, resp);
                break;
            case "/pass/ajax-change-pass":
                content = ajaxUpdatePass(req, resp);
                break;
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }

    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
//            if (!CommonUtil.isAdmin(req)) {
//                resp.sendRedirect("/");
//                return "";
//            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "apps_list"));
            dic.setVariable("PAGE_TITLE", "Tài khoản");

            UserModel userModel = UserModel.getInstance();
            List<UserData> userList = userModel.getUser(0, -1);
            for (UserData userData : userList) {
                TemplateDataDictionary section = dic.addSection("LIST_USER");
                section.setVariable("USER_ID", userData.getId());
                section.setVariable("USER_NAME", userData.getUsername());
                section.setVariable("USER_ROLE", userData.getType().getName());
            }

            Template template = RenderModel.getAdminCTemplate("user_manage");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminUserController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }

    private String ajaxAddNewUser(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
//        if (!CommonUtil.isAdmin(req)) {
//            return CommonUtil.toPermissionDenied();
//        }

        String content;
        int error = 0;
        String msg = "Thêm tài khoản thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            String u = req.getParameter("u") != null ? req.getParameter("u") : "";
            String p = req.getParameter("p") != null ? req.getParameter("p") : "";
            String r = req.getParameter("r") != null ? req.getParameter("r") : "";

            if (u.equalsIgnoreCase("")) {
                msg = "Tên tài khoản không được trống.";
                error = -1;
            }

            if (p.equalsIgnoreCase("")) {
                msg = "Mật khẩu không được trống.";
                error = -1;
            }

            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);
                UserModel userModel = UserModel.getInstance();
                UserData userData = new UserData(u, p, UserType.getById(Integer.parseInt(r)));
                String uid = userModel.addUser(userData);
                if (uid.isEmpty()) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.ACCOUNT_ADD, uid, u);
                }
                data.put("id", uid);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    private String ajaxEditUser(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.isAdmin(req)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Chỉnh sửa tài khoản thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            String p = req.getParameter("p") != null ? req.getParameter("p") : "";
            String r = req.getParameter("r") != null ? req.getParameter("r") : "0";

            if (id.equalsIgnoreCase("")) {
                msg = "Id tài khoản không được trống.";
                error = -1;
            }

            if (error == 0) {
                if (!p.equalsIgnoreCase("")) {
                    p = CommonUtil.md5(p);
                }
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);
                UserData userData = new UserData(id, "", p, UserType.getById(Integer.parseInt(r)), null, 0);
                UserModel userModel = UserModel.getInstance();
                UserData userEdit = userModel.getUserById(id);
                String userName = userEdit.getUsername();
                boolean updateAccount = userModel.updateUser(userData);
                if (!updateAccount) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.ACCOUNT_EDIT, id, userName);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }

    private String ajaxDeleteUser(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.isAdmin(req)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Xoá tài khoản thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";

            if (id.equalsIgnoreCase("")) {
                msg = "Id tài khoản không được trống.";
                error = -1;
            }

            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);
                UserModel userModel = UserModel.getInstance();
                UserData userData = userModel.getUserById(id);
                String userName = userData.getUsername();
                boolean deleteAccount = userModel.deleteUser(id);
                if (!deleteAccount) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.ACCOUNT_DELETE, id, userName);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }

    private String ajaxGetAccess(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.isAdmin(req)) {
            return CommonUtil.toPermissionDenied();
        }

        String content = "";
        int error = 0;
        String msg = "Lấy quyền thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";

            if (id.isEmpty()) {
                msg = "Id tài khoản không hợp lệ.";
                error = -1;
            }

            if (error == 0) {
                TemplateDataDictionary dic = TemplateDictionary.create();
                UserModel userModel = UserModel.getInstance();
                List<String> lstRole = userModel.getUserAccess(id);
                for (UserRole role : EnumSet.allOf(UserRole.class)) {
                    String rid = role.getRole();
                    TemplateDataDictionary addSection = dic.addSection("ACCESS_LIST");
                    addSection.setVariable("ACCESS_ID", rid);
                    addSection.setVariable("ACCESS_NAME", role.getName());

                    if (lstRole != null && lstRole.contains(rid)) {
                        addSection.showSection("ACCESS_GAIN");
                    }
                    if (role.isParent()) {
                        addSection.showSection("ACCESS_PARENT");
                    } else {
                        addSection.showSection("ACCESS_CHILD");
                    }
                }
                Template template = RenderModel.getAdminCTemplate("tmp_permission_table");
                content = template.renderToString(dic);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, content);
        return content;
    }

    private String ajaxUpdateAccess(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.isAdmin(req)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Chỉnh sửa tài khoản thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            String p = req.getParameter("permis") != null ? req.getParameter("permis") : "";
            if (id.equalsIgnoreCase("")) {
                msg = "Id tài khoản không được trống.";
                error = -1;
            }
            SessionModel sessionModel = SessionModel.getInstance();
            String userLogin = sessionModel.getUserLogin(req);
            UserModel userModel = UserModel.getInstance();
            UserData account = userModel.getUserByName(userLogin);
            if (account.getType().getId() != UserType.ADMIN.getId()) {
                msg = "Tài khoản không được phép thực hiện thao tác này.";
                error = -1;
            }

            if (error == 0) {
                boolean updateAccount = userModel.updateUserAccess(id, p);
                if (!updateAccount) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }

    private String ajaxUpdatePass(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);

        String content;
        int error = 0;
        String msg = "Chỉnh sửa tài khoản thành công.";
        try {
            String r = req.getParameter("r") != null ? req.getParameter("r") : "";
            String p = req.getParameter("p") != null ? req.getParameter("p") : "";
            if (p.equalsIgnoreCase("") || r.equalsIgnoreCase("")) {
                msg = "Chưa nhập đủ mật khẩu.";
                error = -1;
            }

            if (!p.equalsIgnoreCase(r)) {
                msg = "Nhập mật khẩu không khớp.";
                error = -1;
            }

            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);

                UserModel userModel = UserModel.getInstance();
                UserData account = userModel.getUserByName(userLogin);

                boolean updateUserPass = false;
                if (account != null) {
                    account.setPasswdMD5(CommonUtil.md5(p));
                    updateUserPass = userModel.updateUserPass(account);
                }

                if (!updateUserPass) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.ACCOUNT_CHANGE_PASS, account.getId(), account.getUsername());
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }

    private String renderChangePass(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        String content = "";
        TemplateDataDictionary dic = TemplateDictionary.create();
        try {
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, ""));
            dic.setVariable("PAGE_TITLE", "Đổi mật khẩu");

            Template template = RenderModel.getAdminCTemplate("user_pass");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminUserController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
}
